package com.itheima.service;

import com.itheima.common.R;
import com.itheima.mapper.CategoryMapper;
import com.itheima.mapper.DishMapper;
import com.itheima.pojo.Category;
import com.itheima.pojo.Employee;
import com.itheima.pojo.Page;
import com.itheima.pojo.Setmeal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author wuyiqiang
 * @2022/6/14 13:37
 */
@Service
public class CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealService setmealService;

    /**
     * 新增分类
     *
     * @param category
     * @return
     */
    public int add(Category category) {
        return categoryMapper.add(category);
    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    public R<Page> page(Integer page, Integer pageSize) {
        Integer pageMin = (page - 1) * pageSize;
        List<Category> page1 = categoryMapper.page(pageMin, pageSize);

        Page page2 = new Page();
        //设置返回页的总条数
        page2.setTotal(categoryMapper.countPage());
        //设置返回页的每页数量
        page2.setSize(pageSize);
        if (page1 != null) {
            //设置返回页返回类对象的当前页
            page2.setCurrent(page);
            //将获得到的数据写进返回类中
            page2.setRecords(page1);
            return R.success(page2);
        } else {
            return R.error("没有数据了");
        }

    }

    /**
     * 下拉查询
     * @param type
     * @return
     */
    public List<Category> dropDown(Integer type){
       return categoryMapper.dropDown(type);
    }

    /**
     * 删除分类
     * @param id
     * @return
     */
    public R delete(String id ){
        try {
            int countDish = dishMapper.selectByCid(id);
            if (countDish>0){
              return   R.error("当前分类下联了菜品，不能删除");
            }
            Setmeal countSetmeal = setmealService.selectByCid(id);
            if (countSetmeal!=null){
                return R.error("当前分类下联了套餐，不能删除");
            }
        } catch (Exception e) {
            System.out.println("删除分类信息时，没有对应的菜品或者套餐");
        }

        categoryMapper.delete(id);
        return R.success("分类信息删除成功");
    }

    /**
     * 修改分类
     * @param category
     * @return
     */
    public int update(Category category){
      return   categoryMapper.update(category);
    }

}
